package com.smt.modules.app.utils;

import com.aliyun.oss.model.OSSObject;
import com.smt.common.utils.AliyunOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangyi
 * @date 2018/11/7 9:49
 */
@Component
@Slf4j
public class ZipOssUtils {

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    /**
     * 远程压缩文件
     *
     * @param fileUrl
     * @param response
     */
    public void loadFile(List<String> fileUrl, HttpServletResponse response) throws Exception{
        //这里，我写了一个将多个文件打包为zip的方法doZip()，doZip()返回生成的zip路径
        String zipName = doZIP("zipname", fileUrl);
        //响应头部
        response.setHeader("Content-disposition", "attachment;filename=order_" + "11111" + ".zip");
        //通过zip路径实例化inputStream流
        InputStream inputStreamzip = new FileInputStream(new File(zipName));

        OutputStream os = response.getOutputStream();
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStreamzip.read(b)) > 0) {
            os.write(b, 0, length);
        }
        os.close();
        inputStreamzip.close();
    }


    /**
     * 文件打包
     *
     * @param zipname
     * @param files
     * @return
     * @throws Exception
     */
    public String doZIP(String zipname, List<String> files) throws Exception {
        //doZIP(命名的打包文件名，传递过来的File数组)
        byte[] buffer = new byte[1024];
        String strZipName = zipname;
        OSSObject ossObject = null;
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipName));
        out.setEncoding("GBK");
        for (int i = 0; i < files.size(); i++) {
            String fileUrl = files.get(i);
            ossObject = aliyunOSSUtil.getFileStream(fileUrl);
            FileInputStream fis = (FileInputStream) ossObject.getObjectContent();
            out.putNextEntry(new ZipEntry(new String(files.get(i).getBytes(), "Shift_JIS")));
            int len;
            //读入需要下载的文件的内容，打包到zip文件
            while ((len = fis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.closeEntry();
            fis.close();
        }
        out.close();
        ossObject.close();
        return strZipName;
    }
}
